package com.google.code.roledroid;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class CharacterEditActivity extends Activity {

	Long _id = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_character_edit);
        
        // check if we have a stringId in the extra's 
        Bundle b = this.getIntent().getExtras();
        
        if(b != null && !b.isEmpty()) {
        	// we must fill the view with the information form the database
        	 
        	_id = b.getLong("rowId");
        	
        	// 	Initializing the database
            CharacterDBHelper Db = new CharacterDBHelper(this);
            
            CharacterDBHelper.Row row = Db.fetchRow(_id);
            
            EditText eName   = (EditText)findViewById(R.id.editText_name);
            
            eName.setText(row.name);        
            
            // Closing Database
            Db.close();            
        }        	
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_character_edit, menu);
        return true;
    }
    
    public void saveAndQuit(View view) {    	
    	// 	Initializing the database
        CharacterDBHelper Db = new CharacterDBHelper(this);
        
        EditText eName   = (EditText)findViewById(R.id.editText_name);
        
    	// Creating new entry	   		    	        
    	if( _id == null) {	        		
	        // TODO: error prone make some input checks here!
	        Db.createRow(eName.getText().toString());	        	        
    	}
    	else {
    		// Editing an existing entry    		                        
            Db.updateRow(_id, eName.getText().toString());    		
    	}
    	
    	Db.close();
    	
    	Intent i = this.getIntent();
    	i.putExtra("resultName", eName.getText().toString());
    	setResult(RESULT_OK, i);    
    	finish();
    }
}
